const Article = require('../../models/article')
const Tag = require('../../models/tag')

module.exports = (req, res) => {
  var formData = {}
  req.body.oldTag = JSON.parse(req.body.oldTag)
  req.body.newTag = JSON.parse(req.body.newTag)
  req.body.allTag = JSON.parse(req.body.allTag)
  formData._id = req.body._id
  formData.title = req.body.title
  formData.author = req.body.author
  formData.tag = []
  formData.content = req.body.content
  formData.commentArea = req.body.commentArea
  formData.last_modified_time = new Date
  // console.log(req.body);

  var oldTag = req.body.oldTag
  var newTag = req.body.newTag
  var allTag = req.body.allTag

  /* 
    1、原来的标签没有了
  */
  for (let i = 0; i < oldTag.length; i++) {
    // console.log(oldTag[i]);
    // console.log(newTag.indexOf(oldTag[i]));
    if (newTag.indexOf(oldTag[i]) === -1) {
      // 修改allTag里的tag_number - 1
      for (let j = 0; j < allTag.length; j++) {
        if (oldTag[i] === allTag[j].tag_name) {
          allTag[j].tag_number = parseInt(allTag[j].tag_number) - 1
          allTag[j].tag_number = allTag[j].tag_number.toString()
          if (allTag[j].tag_number < 0) {
            allTag[j].tag_number = 0
          }
        }
      }
    }
  }
  /* 
    2、找出新添加的标签名，并使allTag + 1
    3、某些标签没有修改
  */
  for (let i = 0; i < newTag.length; i++) {
    if (oldTag.indexOf(newTag[i]) === -1) {
      for (let q = 0; q < allTag.length; q++) {
        if (newTag[i] === allTag[q].tag_name) {
          allTag[q].tag_number = parseInt(allTag[q].tag_number) + 1
          allTag[q].tag_number = allTag[q].tag_number.toString()
          formData.tag.push(allTag[q])
        }
      }
      // console.log(newTag[i]);
      // console.log(formData.tag);
    }
    if (oldTag.indexOf(newTag[i]) !== -1) {
      for (let a = 0; a < allTag.length; a++) {
        if (newTag[i] === allTag[a].tag_name) {
          formData.tag.push(allTag[a])
        }
      }
    }
    // console.log(formData.tag);
  }

  /* 
    formData.tag数据格式校验成功，准备插入数据库Article
  */
  // console.log(formData.tag);

  /*
    allTag所有标签数量核对成功，准备插入数据库Tag
  */
  // console.log(allTag);

  const tag_id = '62162ed14c4270244c5f60db'
  Tag.findByIdAndUpdate({_id:tag_id},{tags:allTag},(err,tagDoc) => {
    console.log('Tag数据更新成功');
  })

  Article.findByIdAndUpdate({
    _id: formData._id
  }, formData, (err, articleDoc) => {
    // 因为更新后返回的数据是旧数据，所以重新查询新数据
    Article.findById({ _id: formData._id }, (err, newArticleDoc) => {
      if (err) {
        return res.status(500).json({
          err_code: 500,
          message: err.message
        })
      }
      res.status(200).json({
        err_code: 0,
        data: newArticleDoc,
        message: '数据修改成功'
      })
      // console.log(newArticleDoc);
    })
  })

}